package com.hmdp.service.impl;

import cn.hutool.core.util.BooleanUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hmdp.dto.Result;
import com.hmdp.entity.Shop;
import com.hmdp.mapper.ShopMapper;
import com.hmdp.service.IShopService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.utils.CacheClient;
import com.hmdp.utils.RedisConstants;
import com.hmdp.utils.RedisData;
import com.hmdp.utils.SystemConstants;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.geo.Distance;
import org.springframework.data.geo.GeoResult;
import org.springframework.data.geo.GeoResults;
import org.springframework.data.redis.connection.RedisGeoCommands;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.domain.geo.GeoReference;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.*;
import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

import static com.hmdp.utils.RedisConstants.*;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 *
 */
@Service
public class ShopServiceImpl extends ServiceImpl<ShopMapper, Shop> implements IShopService {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    //缓存工具类
    @Autowired
    private CacheClient cacheClient;



    @Override
    public Result queryById(Long id) {
        //缓存穿透
        Shop shop = queryWithPassThough(id);
        //工具类解决缓存穿透
        //Shop shop = cacheClient
        // .queryWithPassThough(CACHE_SHOP_KEY, id, Shop.class, this::getById, CACHE_SHOP_TTL, TimeUnit.MINUTES);

        //TODO JMeter压测 用互斥锁解决缓存击穿
        //Shop shop = queryWithMute(id);

        //TODO JMeter压测
        //用逻辑过期时间解决缓存击穿
        //Shop shop = queryWithLogicalExpire(id);
        //工具类解决缓存击穿
//        TODO JMeter压测
        //Shop shop = cacheClient
              //  .queryWithLogicalExpire(CACHE_SHOP_KEY, id, Shop.class, this::getById, CACHE_SHOP_TTL, TimeUnit.SECONDS);


        if (shop == null) {
            return Result.fail("店铺不存在!");
        }
        //返回
        return Result.ok(shop);
    }

    private static final ExecutorService CACHE_REBUILD_EXECUTOR = Executors.newFixedThreadPool(10);

    //用逻辑过期时间解决缓存击穿
    public Shop queryWithLogicalExpire(Long id){
        String key = CACHE_SHOP_KEY + id;

        //从redis中查询商铺缓存
        String shopJson = stringRedisTemplate.opsForValue().get(key);

        //判断是否存在
        if (StrUtil.isBlank(shopJson)) {
            //缓存未命中直接返回
            return null;
        }
        //命中缓存，需要先把json反序列化为对象
        RedisData redisData = JSONUtil.toBean(shopJson, RedisData.class);
        Shop shop = JSONUtil.toBean( (JSONObject) redisData.getData(), Shop.class);
        LocalDateTime expireTime = redisData.getExpireTime();
        //判断是否过期
        if (expireTime.isAfter(LocalDateTime.now())){//是否是当前时间之后，是则未过期
            //未过期，直接返回店铺信息
            return shop;
        }

        //已过期，需要缓存重建
        //重建缓存
        //获取互斥锁
        String localKey = LOCK_SHOP_KEY + id;
        Boolean isLock = tryLock(localKey);
        //判断是否获取成功
        if (isLock){
            //TODO 注意：获取锁成功应该再次检测redis缓存是否存在，做doubleCheck,如果存在则无需重建
            //成功，开启独立线程实现缓存重建  并设置逻辑过期时间
            CACHE_REBUILD_EXECUTOR.submit(()->{
                try {
                    //重建缓存
                    this.saveShop2Redis(id,30L);
                } catch (Exception e) {
                    throw new RuntimeException(e);
                }finally {
                    //释放锁
                    unlock(localKey);
                }
            });
        }

        //返回过期的店铺信息

        return shop;
    }

    //用互斥锁解决缓存击穿
    public Shop queryWithMute(Long id){
        String key = CACHE_SHOP_KEY + id;

        //从redis中查询商铺缓存
        String shopJson = stringRedisTemplate.opsForValue().get(key);

        //判断缓存是否存在
        if (StrUtil.isNotBlank(shopJson)) {//这里shopJson是""会返回false
            //存在则返回,将json转成对象,注意有可能是空对象
            Shop shop = JSONUtil.toBean(shopJson, Shop.class);
            //return Result.ok(shop);
            return shop;
        }
        //判断命中的是否是空字符串，也就是判断是否为""
        if(shopJson!=null){
            //返回错误信息
            //return Result.fail("店铺信息不存在");
            return null;
        }

        //实现缓存重建
        //获取互斥锁,不用synchronized 也不用lock,用redis的setnx的原子性

        String lockKey = "lock:shop："+id;
        Shop shop = null;
        try {
            Boolean isLock = tryLock(lockKey);
            //判断释放获取成功
            if(!isLock){
                //获取失败，则休眠并重试
                Thread.sleep(50);
                queryWithMute(id);//递归重试
            }


            //获取成功，根据id查询数据库
            //TODO 注意：获取锁成功应该再次检测redis缓存是否存在，做doubleCheck,如果存在则无需重建
            shop = getById(id);
            //模拟重建延时
            Thread.sleep(200);

            //数据库找不到，返回错误
            if(shop==null){
                //防止缓存穿透，缓存空对象，缓存空字符串
                //将空值写入Redis
                stringRedisTemplate.opsForValue().set(key,"",CACHE_NULL_TTL, TimeUnit.MINUTES);

                //返回错误信息
                //return Result.fail("店铺不存在");
                return null;
            }

            //存在，先转成json再写入redis
            stringRedisTemplate.opsForValue().set(key,JSONUtil.toJsonStr(shop),CACHE_SHOP_TTL, TimeUnit.MINUTES);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }finally {
            //释放互斥锁
            unlock(lockKey);
        }

        //返回
        //return Result.ok(shop);
        return shop;
    }

    //防止缓存穿透
    public Shop queryWithPassThough(Long id){
        String key = CACHE_SHOP_KEY + id;

        //从redis中查询商铺缓存
        String shopJson = stringRedisTemplate.opsForValue().get(key);

        //判断是否存在
        if (StrUtil.isNotBlank(shopJson)) {//这里shopJson是""会返回false
            //存在则返回,将json转成对象,注意有可能是空对象
            Shop shop = JSONUtil.toBean(shopJson, Shop.class);
            //return Result.ok(shop);
            return shop;
        }
        //判断命中的是否是空字符串，也就是判断是否为""
        if(shopJson!=null){
            //返回错误信息
            //return Result.fail("店铺信息不存在");
            return null;
        }

        //什么都没命中，也就是null
        //不存在，根据id查询数据库
        Shop shop = getById(id);

        //数据库找不到，返回错误
        if(shop==null){
            //防止缓存穿透，缓存空对象，缓存空字符串
            //将空值写入Redis
            stringRedisTemplate.opsForValue().set(key,"",CACHE_NULL_TTL, TimeUnit.MINUTES);

            //返回错误信息
            //return Result.fail("店铺不存在");
            return null;

        }

        //存在，先转成json再写入redis
        stringRedisTemplate.opsForValue().set(key,JSONUtil.toJsonStr(shop),CACHE_SHOP_TTL, TimeUnit.MINUTES);
        //返回
        //return Result.ok(shop);
        return shop;
    }

    //尝试获取锁,设置过期时间防止意外没释放锁导致死锁
    private Boolean tryLock(String key){
        Boolean flag = stringRedisTemplate.opsForValue().setIfAbsent(key, "1", 10, TimeUnit.SECONDS);
        return BooleanUtil.isTrue(flag);
    }
    //释放锁
    private void unlock(String key){
        stringRedisTemplate.delete(key);
    }

    //将逻辑过期时间写入redis,重建缓存
    public void saveShop2Redis(Long id,Long expireSeconds) throws InterruptedException {
        //查询店铺数据
        Shop shop = getById(id);
        //模拟缓存重建延时
        Thread.sleep(200);
        //封装逻辑过期时间
        RedisData redisData = new RedisData();
        redisData.setData(shop);
        redisData.setExpireTime(LocalDateTime.now().plusSeconds(expireSeconds));//当前时间+秒数
        //写入redis,不加ttl,过期时间由自己控制
        stringRedisTemplate.opsForValue().set(CACHE_SHOP_KEY+id,JSONUtil.toJsonStr(redisData));
    }

    @Override
    @Transactional
    public Result update(Shop shop) {
        Long id = shop.getId();
        if(id==null){
            return Result.fail("店铺id不能为空");
        }
        //更新数据库
        updateById(shop);
        //删除缓存
        stringRedisTemplate.delete(CACHE_SHOP_KEY +shop.getId());
        return Result.ok();
    }

    @Override
    public Result queryShopByType(Integer typeId, Integer current, Double x, Double y) {
        //判断是否需要根据坐标查询
        if (x==null||y==null){
            //不需要坐标查询，按数据库查询 根据类型分页查询
        Page<Shop> page = query()
                .eq("type_id", typeId)
                .page(new Page<>(current, SystemConstants.DEFAULT_PAGE_SIZE));
        // 返回数据
        return Result.ok(page.getRecords());
        }
        //计算分页参数
        int from = (current-1)*SystemConstants.DEFAULT_PAGE_SIZE;
        int end = current*SystemConstants.DEFAULT_PAGE_SIZE;
        //查询redis，按照距离排序，分页，结果：shopId,distance
        String key = SHOP_GEO_KEY +typeId;
        GeoResults<RedisGeoCommands.GeoLocation<String>> results = stringRedisTemplate.opsForGeo()
                //geosearch key bylonlat x y byradius 10 withdistance
                // bylonlat根据地理坐标  byradius根据半径 默认米 withdistance结果带上距离
                .search(
                        key,
                        GeoReference.fromCoordinate(x, y),
                        new Distance(5000),
                        RedisGeoCommands.GeoSearchCommandArgs.newGeoSearchArgs().includeDistance().limit(end));
        //解析出id
        if (results==null){
            return Result.ok(Collections.emptyList());
        }
        List<GeoResult<RedisGeoCommands.GeoLocation<String>>> list = results.getContent();
        if (list.size()<=from){//解决bug,滑倒最底下会报错
            //没有下一页了，结束
            return Result.ok(Collections.emptyList());
        }
        //limit(end)默认截取0-end的部分，需要截取from-end的部分
        //创建list封装店铺id
        List<Long> ids = new ArrayList<>(list.size());
        //创建map使distance和店铺id一一对应
        Map<String,Distance> distanceMap = new HashMap<>(list.size());
        list.stream().skip(from).forEach(res->{
            //获取店铺id
            String shopIdStr = res.getContent().getName();
            //存进list
            ids.add(Long.valueOf(shopIdStr));
            //获取距离
            Distance distance = res.getDistance();
            //存进map
            distanceMap.put(shopIdStr,distance);
        });
        //根据id查询店铺
        String idStr = StrUtil.join(",", ids);
        List<Shop> shops = query().in("id", ids).last("ORDER BY FIELD(id," + idStr + ")").list();
        //将距离写入shop
        for (Shop shop : shops) {
            shop.setDistance(distanceMap.get(shop.getId().toString()).getValue());
        }
        //返回
        return Result.ok(shops);
    }
}
